import 'dart:convert';
import 'package:base_lib/common/base/base_theme_state.dart';
import 'package:base_lib/dictionary/dictionary_provider.dart';
import 'package:base_lib/index.dart';
import 'package:base_lib/router/parameters.dart';
import 'package:base_lib/router/routers.dart';
import 'package:base_lib/theme/theme_global.dart';
import 'package:doctor_prescribe_lib/offline/basic_info/bloc.dart';
import 'package:doctor_prescribe_lib/repository/http.dart';
import 'package:flutter/material.dart';
import 'package:doctor_prescribe_lib/chinese_medicine/prescription_page/bloc.dart';
import '../../western_medicine/medical_search/entity/medical_search_entity.dart'
    as MedicalSearchBean;

///用法用量
class ChineseDosagePage extends StatefulWidget {
  final Parameters parameters;

  ChineseDosagePage(this.parameters);

  @override
  State<StatefulWidget> createState() {
    int orgTypeID = parameters.getInt("orgTypeID") ?? 0;
    MedicalSearchBean.Datas item = parameters.getObj('item');

    return _State(orgTypeID, item);
  }
}

class _State extends BaseThemeState<ChineseDosagePage> {
  int orgTypeID;
  MedicalSearchBean.Datas item;

  _State(this.orgTypeID, this.item);

  var tsLeft = TextStyle(color: Colors.black, fontSize: 16);
  var tsRight = TextStyle(color: Colors.grey, fontSize: 14);

  int medicineAmount = 0;
  String usage = '';
  int cacheIndex;

  @override
  void initState() {
    super.initState();
    cacheIndex = ChinesePrescriptionPageBloc.rxMedicineList
        .indexWhere((element) => element.medicineID == item.medicineID);

    if (cacheIndex != -1) {
      item = ChinesePrescriptionPageBloc.rxMedicineList[cacheIndex];
    }

    FLog(json.encode(item));

    medicineAmount = item.medicineAmount ?? 0;
    usage = item.usage ?? '';

    setDefaultDosage();
  }

  @override
  Widget buildChild(BuildContext context, MTheme theme) {
    return Scaffold(
      appBar: AppBar(
        leading: BackButton(
          onPressed: () {
            Routers.pop(context);
          },
        ),
        centerTitle: true,
        title: Text('用法用量'),
        actions: [
          FlatButton(
              onPressed: () {
                doSave();
              },
              child: Text(
                '保存',
                style: TextStyle(color: Colors.white),
              ))
        ],
      ),
      body: LayoutBuilder(
        builder: (context, cons) {
          return Container(
            constraints: cons,
            color: theme.themeColor.themeBgColor,
            child: SingleChildScrollView(
              child: Column(
                children: [
                  Container(
                    padding: EdgeInsets.all(15),
                    alignment: Alignment.centerLeft,
                    child: Text(
                      item.medicineName,
                      style: tsLeft.copyWith(fontSize: 20),
                    ),
                  ),
                  ColoredBox(
                    color: Colors.white,
                    child: Row(
                      children: [
                        10.hGapDp,
                        Text(
                          '*',
                          style: tsLeft.copyWith(color: Colors.red),
                        ),
                        Text(
                          '用量',
                          style: tsLeft,
                        ),
                        10.hGapDp,
                        Expanded(
                          child: TextField(
                            controller: TextEditingController(
                                text: medicineAmount == 0
                                    ? ''
                                    : medicineAmount.toString()),
                            textAlign: TextAlign.right,
                            keyboardType: TextInputType.number,
                            decoration: InputDecoration(
                                border: InputBorder.none,
                                hintStyle: tsRight,
                                hintText: '输入用量'),
                            onChanged: (str) {
                              if (str.isEmpty) return;
                              try {
                                medicineAmount = int.parse(str);
                              } catch (e) {
                                print(e);
                                ToastUtil.warning('请输入正确的数字');
                              }
                            },
                          ),
                        ),
                        10.hGapDp,
                        Text(
                          '克',
                          style: tsRight.copyWith(fontSize: 12),
                        ),
                        10.hGapDp,
                      ],
                    ),
                  ),
                  1.vGapDp,
                  ColoredBox(
                    color: Colors.white,
                    child: Row(
                      children: [
                        10.hGapDp,
                        Text(
                          ' ',
                          style: tsLeft.copyWith(color: Colors.red),
                        ),
                        Text(
                          '用法',
                          style: tsLeft,
                        ),
                        Spacer(),
                        Text(
                          usage.isNotEmpty ? usage : '请选择',
                          style: tsRight,
                        ),
                        IconButton(
                            icon: Icon(
                              Icons.arrow_forward_ios,
                              color: Colors.grey,
                              size: 14,
                            ),
                            onPressed: () {
                              showPicker();
                            }),
                        10.hGapDp,
                      ],
                    ),
                  ),
                  100.vGapDp,
                  cacheIndex != -1
                      ? Container(
                          padding: EdgeInsets.all(10),
                          height: 65,
                          width: ScreenAdapter.screenWidthDp,
                          child: RaisedButton(
                            child: Text('删除'),
                            shape: RoundedRectangleBorder(
                                side: BorderSide(color: Colors.red),
                                borderRadius: BorderRadius.circular(15)),
                            color: Colors.red,
                            textColor: Colors.white,
                            onPressed: () {
                              Custom_iOS_Dialog.prompt(context,
                                  content: '确定删除  ${item.medicineName}  ?',
                                  okFn: () {
                                ChinesePrescriptionPageBloc.rxMedicineList
                                    .remove(item);
                                Routers.pop(context, true);
                              });
                            },
                          ),
                        )
                      : SizedBox(),
                  30.vGapDp,
                ],
              ),
            ),
          );
        },
      ),
    );
  }

  void showPicker() async {
    var result = await DictionaryProvider.getChieseMedicalTreatment();
    if (result.isSuccess) {
      var jsonList = result.data['data'] as List;
      List<String> list =
          jsonList.map((element) => element['dictName'].toString()).toList();
      WPicker.showWPicker<String>(
          context: context,
          selectedItem: usage,
          itemList: list,
          map2string: (e) => e).then((value) {
        if (value is String) {
          setState(() {
            usage = value;
          });
        }
      });
    } else {
      ToastUtil.error(result.error.msg);
    }
  }

  void doSave() {
    if (medicineAmount == null || medicineAmount < 1) {
      ToastUtil.warning('用量填写错误');
      return;
    }

    if (medicineAmount > 999) {
      ToastUtil.warning('用量最大不能超过999g!');
      return;
    }

    if (usage == null || usage.isEmpty) {
      ToastUtil.warning('请选择用法');
      return;
    }



    double price = item.unitPrice * medicineAmount;
    item
          ..price = price
          ..medicineClassID = 1
          ..medicineClassName = '中药'
          ..specification = ''
          ..medicineAmount = medicineAmount // 用量： 多少g!
          ..unit = 'g' // 中药单位和剂型一样都是g
          ..formType = 'g'
          // ..takeDose =  0 // 中药只有在处方包含 服用剂量
          ..takeFrequence = '' // 中药只有在处方包含 服用频次
          ..takeDirection = usage
          ..usage = usage
          ..course = '' // 无疗程
          ..memo = '' // 无备注
        ;

    if (cacheIndex != -1) {
      ChinesePrescriptionPageBloc.rxMedicineList.removeAt(cacheIndex);
    }

    ChinesePrescriptionPageBloc.rxMedicineList.add(item);

    Routers.pop(context, true);
  }

  void setDefaultDosage() async {
    var result = await PrescribeHttp.getMedicineInfo(item.medicineID);
    if (result.isSuccess) {
      usage = result.data.dosage;
      setState(() {});
    }
  }
}
